const express = require("express")
const router = express.Router()
const { v1: uuidV1 } = require("uuid")
var bodyParser = require("body-parser")

// 创建application/json 解析器
var jsonParser = bodyParser.json()

let connectDAO = require('../connect')
async function dbTrainInfo(sql,processData) {
  //processData为回调方法
  await connectDAO.queryDataBySQL(sql, processData);
}
// 上传文章
router.post("/upload_article", jsonParser, function (req, res) {
	let {
		upload_html,
		coverUrl,
		article_classify,
		article_title,
		article_introduction,
		userId,
	} = req.body
	const sql = `SELECT id,avatarUrl,nickname FROM userInfo where id = '${userId}'`;
    function html2Escape(sHtml) {
        return sHtml.replace(/[<>&"]/g,function(c){return {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c];});
    }
    upload_html = html2Escape(upload_html)
    upload_html = upload_html.replace(/\"/g,"'")
	dbTrainInfo(sql, processData)
	function processData(result) {
		let data = JSON.parse(JSON.stringify(result))
		data = data[0]
        const publish_time =  new Date().getTime()
        const insertsql = 
        `INSERT INTO articles VALUES ('${uuidV1()}','${article_classify}','${coverUrl}','${article_title}','${article_introduction}',"${upload_html}",'${publish_time}','${userId}',0,'[]');`;
        connectDAO.queryDataBySQL(insertsql).then(()=>{
            res.send({ code : 200,msg : "发布成功"})
        }).catch((err)=>{
            res.send({ code : 201,msg : "发布失败，请重试"})
        })
	}
})

// 修改文章
router.post("/update_article", jsonParser, function (req, res) {
    const {
      upload_html,
      coverUrl,
      article_classify,
      article_title,
      article_introduction,
      article_id,
    } = req.body;
    const insertsql = `UPDATE articles a SET a.article_classify = '${article_classify}',a.coverUrl = '${coverUrl}',a.article_title = '${article_title}',a.article_introduction = '${article_introduction}',a.content = '${upload_html}' where id = '${article_id}';`;
    connectDAO.queryDataBySQL(insertsql).then(()=>{
        res.send({ code : 200,msg : "修改成功"});
    }).catch(()=>{
        res.send({ code : 201,msg : "修改失败"});
    })
});

// 读取某个模块文章列表
router.get("/get_article_moduleList", function (req, res) {
    let { module,current } = req.query
    current = (current - 1)*10
    // SELECT articles.*,userinfo.nickname,userinfo.avatarUrl FROM articles,userinfo WHERE articles.userId = userinfo.id and articles.article_classify = 'frontend'  ORDER BY publish_time=1657872442121 DESC LIMIT 0,10;
    dbTrainInfo(`SELECT art.id,art.article_title,art.publish_time,art.commenter,art.coverUrl,art.article_introduction,art.readCount,userInfo.nickname,userInfo.avatarUrl FROM articles as art,userInfo WHERE art.userId = userInfo.id and art.article_classify = '${module}' ORDER BY publish_time DESC LIMIT ${current},10;`,(result)=>{
        let arr = []
        result = JSON.parse(JSON.stringify(result))
        dbTrainInfo(`SELECT like_art FROM userInfo;`,async (re)=>{
            re = JSON.parse(JSON.stringify(re))
            re.forEach(i=>{
                if(JSON.parse(i.like_art).length > 0){
                    arr.push(...JSON.parse(i.like_art))
                }
            })
            result.forEach(i=>{
                delete i.content 
                i.likeCount = 0
                arr.forEach(j=>{
                    if(j == i.id){
                        i.likeCount += 1
                    }
                })
            })
            let total = 0
            await dbTrainInfo(`SELECT count(*) from articles WHERE article_classify = '${module}';`,(res)=>{
                res = JSON.parse(JSON.stringify(res))[0]
                total = res['count(*)']
            })

            res.send({
                code: 200,
                message: "success",
                total,
                article_moduleList:result,
            });
        })
    })
});

// 读指定某条文章内容
router.get("/get_article_content", function (req, res) {
    const { article_id } = req.query;
    let userId = ''
    connectDAO.queryDataBySQL(`UPDATE articles SET readCount = readCount+1 WHERE articles.id = '${article_id}';`) //更新阅读量
    dbTrainInfo(`select * from articles ar where ar.id = '${article_id}';`,(result)=>{
         let data = JSON.parse(JSON.stringify(result))[0]
         userId = data.userId
         dbTrainInfo(`select nickname,avatarUrl from userInfo where id = '${userId}';`,(result)=>{
            let {nickname,avatarUrl} = JSON.parse(JSON.stringify(result))[0]
            res.send({...data,uper:{nickname,avatarUrl}})
         })
    })
});

// 首页文章列表
router.get("/article_list", function (req, res) {
        dbTrainInfo(`SELECT id,article_title,article_introduction,publish_time,commenter FROM articles ORDER BY readCount DESC LIMIT 0,7;`,(result)=>{
            result = JSON.parse(JSON.stringify(result))
            res.send({ code : 200,msg : "ok",result})
        })
});

// 搜索
router.get('/search_article',function(req,res){
    const {serachText} = req.query
    dbTrainInfo(`SELECT articles.article_title,articles.id FROM articles WHERE article_title LIKE '%${serachText}%' OR id LIKE '%${serachText}%';`,(result)=>{
        result = JSON.parse(JSON.stringify(result))
        res.send({ code : 200,msg : "ok",result})
    })
})

// 发表评论
router.put("/put_comment", function (req, res) {
    let {  article_id, userId, comment } = req.body;
    // 评论格式化
    comment = {content:comment,commentTime:(new Date()).getTime() ,commentId:uuidV1()}
    let commenter = []
    dbTrainInfo(`SELECT commenter FROM articles WHERE id = '${article_id}';`,async (result)=>{
        commenter = JSON.parse(JSON.stringify(result))[0].commenter
        commenter = JSON.parse(commenter)
        if(commenter.length > 0 ){// 该文章评论过
            const userComArrIndex = commenter.findIndex(i=>i.userId == userId)
            if(userComArrIndex>=0){//判断该用户是否评论过
                commenter[userComArrIndex].comment.unshift(comment)
                toUpdate()
            }else{
                await dbTrainInfo(`SELECT nickname,avatarUrl FROM userInfo WHERE userInfo.id = '${userId}';`,(result)=>{
                    let {nickname,avatarUrl} = JSON.parse(JSON.stringify(result))[0]
                    commenter.unshift({ comment: [comment], userId,nickname,avatarUrl})
                })
                toUpdate()
            }
        }else{
            await dbTrainInfo(`SELECT nickname,avatarUrl FROM userInfo WHERE userInfo.id = '${userId}';`,(result)=>{
                let {nickname,avatarUrl} = JSON.parse(JSON.stringify(result))[0]
                commenter = [{ comment: [comment],userId, avatarUrl, nickname }]
            })
            toUpdate()
        }
    })
    function toUpdate(){
        commenter = JSON.stringify(commenter)
        connectDAO.queryDataBySQL(`UPDATE articles SET commenter = '${commenter}' WHERE articles.id = '${article_id}';`).then(()=>{
            res.send({ code : 200,msg : "ok"})
        }).catch(()=>{
            res.send({ code : 201,msg : "fail,Please try again"})
        })
    }
})

//获取评论
router.get("/get_comment", function (req, res) {
  const { article_id } = req.query;
  let commenter = []
  dbTrainInfo(`SELECT commenter FROM articles WHERE id = '${article_id}';`,async (result)=>{
    commenter = JSON.parse(JSON.stringify(result))[0].commenter
    commenter = JSON.parse(commenter)
  }).then(()=>{
    res.send({code : 200,msg : "ok",commenter});
  }).catch(()=>{
    res.send({code : 201,msg : "fail"});
  })
});

// 删除评论
router.delete("/delete_comment", function (req, res) {
    const {  article_id, userId,commentId } = req.body;
    let commenter = []
    dbTrainInfo(`SELECT commenter FROM articles WHERE id = '${article_id}';`, (result)=>{
        commenter = JSON.parse(JSON.stringify(result))[0].commenter
        commenter = JSON.parse(commenter)
        let commentIndex = commenter.findIndex(item=>item.userId == userId)
        let deleteIndex = commenter[commentIndex].comment.findIndex(item=>item.commentId == commentId)
        if(deleteIndex >= 0){
            commenter[commentIndex].comment.splice(deleteIndex, 1)
        }else{
            commenter[commentIndex].comment.forEach((i,index)=>{
                deleteIndex = i.replyContent.findIndex(item => item.commentId = commentId)
                if(deleteIndex>=0){
                    commenter[commentIndex].comment[index].replyContent.splice(deleteIndex, 1)
                }
            })
        }
    }).then(()=>{
        toUpdate()
    })
    function toUpdate(){
        commenter = JSON.stringify(commenter)
        connectDAO.queryDataBySQL(`UPDATE articles SET commenter = '${commenter}' WHERE articles.id = '${article_id}';`).then(()=>{
            res.send({ code : 200,msg : "删除成功"})
        }).catch(()=>{
            res.send({ code : 201,msg : "删除失败，请重试"})
        })
    }
});


// 回复评论
router.post('/releaseReply',function(req,res){
    let {article_id,userId,BerepliederId,BecommentId,replyContent} = req.body
    replyContent = {content:replyContent,commentTime:(new Date()).getTime() ,commentId:uuidV1()}
    dbTrainInfo(`SELECT commenter from articles WHERE id = '${article_id}';`,async (result)=>{
        let {commenter} = JSON.parse(JSON.stringify(result))[0]
        commenter = JSON.parse(commenter)
        const BerepliederIndex = commenter.findIndex(i=>i.userId == BerepliederId)
        const BecommentIdIndex = findBecommentIdIndex(commenter[BerepliederIndex].comment)
        function findBecommentIdIndex(arr){
            const index = arr.findIndex(i=>i.commentId == BecommentId)
            if(index>=0){
                return index
            }
        }
        await dbTrainInfo(`SELECT nickname,avatarUrl FROM userInfo WHERE userInfo.id = '${userId}';`,(result)=>{
            let {nickname,avatarUrl} = JSON.parse(JSON.stringify(result))[0]
            commenter[BerepliederIndex].comment[BecommentIdIndex].replyContent ? 
            commenter[BerepliederIndex].comment[BecommentIdIndex].replyContent.unshift({ ...replyContent, userId,nickname,avatarUrl}) :
            commenter[BerepliederIndex].comment[BecommentIdIndex].replyContent = [{ ...replyContent, userId,nickname,avatarUrl}]
            commenter = JSON.stringify(commenter)
            connectDAO.queryDataBySQL(`UPDATE articles SET commenter = '${commenter}' WHERE articles.id = '${article_id}';`).then(()=>{
                res.send({ code : 200,msg : "ok"})
            }).catch(()=>{
                res.send({ code : 201,msg : "fail,Please try again"})
            })
        })
    })
})

// 点赞点踩
router.post('/change_like',function(req,res){
    const {like,unlike, article_id, userId} = req.body
    dbTrainInfo(`SELECT like_art,unlike_art FROM userInfo WHERE id = '${userId}';`, (result)=>{
        let {like_art,unlike_art} = JSON.parse(JSON.stringify(result))[0]
        like_art = JSON.parse(like_art);
        unlike_art = JSON.parse(unlike_art)
        if(like){
            like_art.push(article_id)
            const unIndex =  unlike_art.findIndex(i=> i == article_id) 
            unIndex >=0 ? unlike_art.splice(unIndex,1) : ''
        }
        else if(unlike){
            unlike_art.push(article_id)
            const Index =  like_art.findIndex(i=> i == article_id) 
            Index >=0 ? like_art.splice(Index,1) : ''
        }
        else{
            const unIndex =  unlike_art.findIndex(i=> i == article_id) 
            if(unIndex>=0){
                unlike_art.splice(unIndex,1) 
            }else{
                const Index =  like_art.findIndex(i=> i == article_id) 
                Index >=0 ? like_art.splice(Index,1) : ''
            }
        }
        like_art = JSON.stringify(like_art)
        unlike_art = JSON.stringify(unlike_art)
        connectDAO.queryDataBySQL(`UPDATE userInfo SET like_art = '${like_art}' WHERE userInfo.id = '${userId}';`)
        connectDAO.queryDataBySQL(`UPDATE userInfo SET unlike_art = '${unlike_art}' WHERE userInfo.id = '${userId}';`)
    }).then(()=>{
        res.send({code:200,mas:'成功'})
    }).catch((err)=>{
        res.send({code:201,mas:'失败'})
    })
})
// 收藏
router.post('/change_collection',function(req,res){
    const {collection, article_id, userId} = req.body
    dbTrainInfo(`SELECT collection_art FROM userInfo WHERE id = '${userId}';`, (result)=>{
        let {collection_art} = JSON.parse(JSON.stringify(result))[0]
        collection_art = JSON.parse(collection_art)
        if(collection){
            collection_art.push(article_id)
        }else{
            const Index =  collection_art.findIndex(i=> i == article_id) 
            Index >=0 ? collection_art.splice(Index,1) : ''
        }
        collection_art = JSON.stringify(collection_art)
        connectDAO.queryDataBySQL(`UPDATE userInfo SET collection_art = '${collection_art}' WHERE userInfo.id = '${userId}';`)
    }).then(()=>{
        res.send({code:200,mas:'成功'})
    }).catch((err)=>{
        res.send({code:201,mas:'失败'})
    })
})


// 查询是否点赞点踩，收藏
router.get('/get_like',function(req,res){
    const {userId} = req.query
    if(!userId){
        res.send({code:201,msg:'未登录'})
        return
    }
    dbTrainInfo(`select like_art,unlike_art,collection_art from userInfo where id = '${userId}'`,(result)=>{
        result = JSON.parse(JSON.stringify(result))[0]
        res.send({code:200,msg:'成功',result})
    })
})

// 发布碎碎念
router.put('/send_nagging',function(req,res){
    const {content} = req.body
    const time =  new Date().getTime()
    dbTrainInfo(`INSERT INTO nagging VALUES ('${uuidV1()}','${content}','${time}');`,()=>{
    }).then(()=>{
        res.send({code:200,msg:'成功'})
    }).catch(()=>{
        res.send({code:201,msg:'失败'})
    })
})

router.get('/get_nagging',function(req,res){
    let data = []
    dbTrainInfo(`SELECT * from nagging ORDER BY time DESC;`,(result)=>{
        data = JSON.parse(JSON.stringify(result))
    }).then(()=>{
        res.send({code:200,msg:'成功',data})
    }).catch((err)=>{
        console.log(err);
        res.send({code:201,msg:'失败'})
    })
})

// 所有文章
router.get("/get_articleList",function (req,res) {
    const sql = `SELECT * from articles;`
    dbTrainInfo(sql, (result) => {
      res.send({ code: 200, msg: "获取成功", result })
    });
  })

module.exports = router;
